package me.stone.stanimeclient.ui

import androidx.appcompat.app.AppCompatActivity
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.runBlocking
import me.stone.stanimeclient.core.common.di.ApplicationScope
import me.stone.stanimeclient.core.data.domain.setting.GetDarkThemeModeCase
import me.stone.stanimeclient.core.data.domain.setting.ObserveDarkThemeModeCase
import me.stone.stanimeclient.core.model.DarkThemeMode
import javax.inject.Inject
import javax.inject.Singleton


interface DarkThemeModeDelegate {

    val darkThemeModeFlow: Flow<DarkThemeMode>

    val currentDarkThemeMode: DarkThemeMode

}

@Singleton
class DarkThemeModeImpl @Inject constructor(
    @ApplicationScope val externalScope: CoroutineScope,
    observeDarkThemeModeCase: ObserveDarkThemeModeCase,
    private val getDarkThemeModeCase: GetDarkThemeModeCase
) : DarkThemeModeDelegate {
    override val darkThemeModeFlow: Flow<DarkThemeMode> = observeDarkThemeModeCase(Unit).map {
        it.dataOrNull ?: DarkThemeMode.System
    }.stateIn(externalScope, SharingStarted.Eagerly, currentDarkThemeMode)

    override val currentDarkThemeMode: DarkThemeMode
        get() = runBlocking {
            getDarkThemeModeCase(Unit).dataOrNull ?: DarkThemeMode.System
        }
}

@Suppress("UNUSED")
@InstallIn(SingletonComponent::class)
@Module
abstract class DarkThemeModeDelegateModule {
    @Singleton
    @Binds
    abstract fun provideDarkThemeModeDelegate(
        impl: DarkThemeModeImpl
    ): DarkThemeModeDelegate
}


fun AppCompatActivity.updateDarkThemeMode(mode: DarkThemeMode) {
    if (delegate.localNightMode != mode.modeValue) {
        delegate.localNightMode = mode.modeValue
    }
}